package rsj.api.test;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.fastjson.JSONArray;
import com.rlyy.aibase.db.Dbink;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import common.util.Base64Util;
import common.util.BoxUtil;
import common.util.DateFormat;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.api.user.BaseLink;
import rsj.dao.TestLogDao;
import rsj.db.PostgresqlConn;
import rsj.domain.TestLog;

import java.io.ByteArrayOutputStream;
import java.sql.Connection;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 导出测试列表数据
 *
 * @author yuanqinglong
 * @since 2020/10/19 11:54
 */
@RestController
public class ExportTestResult extends BaseLink {

    TestLogDao testLogDao = TestLogDao.getInstance();

    @Override
    @RequestMapping(value = "rsj_rep_exportTestResult")
    public Box executeLink(Box box) {
        MapNode data = box.getMapNode("data");
        String offlineOrgName = data.getValue("offline_org_name");
        String startTm = null;
        String endTm = null;
        String logTm = data.getValueDef("log_time", null);
        List<String> time = Optional.ofNullable(logTm).map(s -> JSONArray.parseArray(logTm).toJavaList(String.class)).orElse(null);
        if (!CollectionUtils.isEmpty(time) && time.size() == 2) {
            startTm = time.get(0);
            endTm = time.get(1);
        }
        Connection conn = PostgresqlConn.getConnection();
        try {
            MapNode mapNode = testLogDao.testLogList(conn, null, null, offlineOrgName, startTm, endTm);
            String logList = mapNode.getValue("__testLogList__");
            if (StringUtils.isEmpty(logList)) {
                return BoxUtil.errorBox(box, "没有数据可导出");
            }
            JSONArray jsonArray = JSONArray.parseArray(logList);
            List<TestLog> testQueryEntities = jsonArray.toJavaList(TestLog.class);
            return BoxUtil.successBoxToData(box, "成功", this.exportExcel(testQueryEntities));
        } catch (Exception e) {
            e.printStackTrace();
            return BoxUtil.errorBox(box, "导出失败");
        } finally {
            Dbink.close(conn);
        }
    }


    public MapNode exportExcel(List<TestLog> testLogs) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        EasyExcelFactory.write(os, TestLog.class).sheet("模板").doWrite(testLogs);
        String fileContent = Base64Util.encodeByte(os.toByteArray());
        String fileName = String.format("test_log_%s.xlsx", LocalDateTime.now().format(DateFormat.DATE_TIME_RIGHT_NEXT_TO));
        MapNode file = new MapNode();
        file.putNode("file_name", fileName);
        file.putNode("file_content", fileContent);
        return file;
    }


    //private byte[] genBankOrgListRptExcelFile(JSONArray array) {
    //    Map<Integer, List<List<Map<String, Object>>>> datas = new HashMap<>();
    //    int sheetNum = 0;
    //    List<List<Map<String, Object>>> bankListSheet = new ArrayList<>();
    //    if (array != null) {
    //        List<String> numberProps = new ArrayList<>();
    //        String[] properties = new String[]{"num", "Log_Org_Name", "Log_Prod_Id", "Log_Amount", "Log_Time"};
    //        for (int i = 0; i < array.size(); i++) {
    //            JSONObject bean = array.getJSONObject(i);
    //            bean.put("num", i + 1);
    //        }
    //        ExcelUtils.genExcelSheetData(bankListSheet, array, properties, numberProps);
    //    }
    //    datas.put(sheetNum + 1, bankListSheet);
    //    List<String[]> repHeaders = new ArrayList<>();
    //    repHeaders.add(new String[]{"序号", "线下测试机构", "测试接口", "测试量", "测试日期"});
    //
    //    Map<Integer, List<String[]>> header = new HashMap<>();
    //    header.put(0, repHeaders);
    //    return ExcelUtils.toExcel(datas, header, null, null, 0, new String[]{"报表导出"});
    //}
}
